﻿using System.Text.RegularExpressions;

namespace Nextensions.Numbers
{
    public static class Conversions
    {
        public static int FromBinary(string Binary)
        {
            if(string.IsNullOrEmpty(Binary))
                return 0;

            Binary = Binary.Trim();

            if(!Regex.IsMatch(Binary, @"^[0-1]+$"))
                return 0;

            int real = 0;

            for (int i = 0; i < Binary.Length; i++)
            {
                int ci = Binary.Length - i - 1;
                if(Binary[ci] == '1')
                    real += 1 << i;
            }

            return real;
        }

        public static int FromSynchsafe(byte[] bytes)
        {
            int real = 0;
            byte abs = 0;

            for (int i = bytes.Length - 1; i >= 0; i--)
            {
                for (byte bit = 0; bit < 7; bit++)
                {
                    byte bitVal = (byte)(1 << bit);

                    if ((bytes[i] & bitVal) == bitVal)
                        real += 1 << abs;

                    abs++;
                }
            }

            return real;
        }
    }
}
